package tech.aistar.corejava.day17.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author success
 * @version 1.0
 * @description:本类用来演示:
 * @date 2019/8/6 0006
 */
public class MethodDemo {
    public static void main(String[] args) throws NoSuchMethodException {
        Class<?> c = Point.class;

        //获取所有的声明的方法
        Method[] methods = c.getDeclaredMethods();

        for (int i = 0; i < methods.length; i++) {
            //1. 获取修饰符
            System.out.print(Modifier.toString(methods[i].getModifiers())+"\t");

            //2.获取返回类型
            System.out.print(methods[i].getReturnType().getSimpleName()+"\t");

            //3.获取方法的名称
            System.out.print(methods[i].getName()+" ");

            //4.获取方法的参数列表
            StringBuilder params = new StringBuilder("(");

            //5.获取参数列表
            Class<?>[] types = methods[i].getParameterTypes();

            for (int j = 0; j < types.length; j++) {
                if(j!=types.length-1){
                    params.append(types[j].getSimpleName()+",");
                }else{
                    params.append(types[j].getSimpleName());
                }
            }
            params.append(")");
            System.out.println(params);
        }
        System.out.println("=============");
        try {
            Point p = (Point) c.newInstance();

            //根据方法的名称以及参数列表来获取该方法对应的method类型
            //默认的就是调用test的空参方法
            //Method m = c.getDeclaredMethod("Test");
            //反射调用方法
            //m.invoke(p);

            //Method m = c.getDeclaredMethod("Test",new Class<?>[]{});
            //m.invoke(p,null);

//            Method m = c.getDeclaredMethod("Test",int.class);
//            m.invoke(p,10);

//            Method m = c.getDeclaredMethod("Test",int.class,String.class);
//            m.invoke(p,10,"tom");

//            Method m = c.getDeclaredMethod("Test",new Class<?>[]{int.class,String.class});
//            m.invoke(p,new Object[]{10,"jack"});

            //私有的
          //  Method m = c.getDeclaredMethod("testPrivate");
            //调用私有的成员
           // m.setAccessible(true);
           // m.invoke(p);

            //静态的
            //Method m = c.getDeclaredMethod("staticMethod");
           // m.invoke(null);

            Method m = c.getDeclaredMethod("get");

            String result = (String) m.invoke(p);
            System.out.println(result);

            System.out.println(p);

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
